﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using BP.OA;
namespace CCOA.App.NOTICE
{
    public partial class NewNotice : System.Web.UI.Page
    {
        #region //1.PI
        //权限控制
        private string FuncNo = null;

        /// <summary>
        /// 当前用户部门列表
        /// </summary>
        private DataTable CurUserDepts
        {
            get
            {
                if (BP.WF.Glo.OSModel == BP.Sys.OSModel.OneOne)
                {
                    return BP.DA.DBAccess.RunSQLReturnTable("SELECT * FROM Port_Dept WHERE No IN (SELECT FK_Dept FROM port_empdept WHERE FK_Emp='" + BP.Web.WebUser.No + "')");
                }
                return BP.OA.GPM.GetUserDeptsOfDatatable(BP.Web.WebUser.No);
            }
        }
        /// <summary>
        /// 获取通知类型
        /// </summary>
        /// <returns></returns>
        private DataTable GetAllNoticeCategory()
        {
            return BP.DA.DBAccess.RunSQLReturnTable("select No,Name from OA_NoticeCategory order by No");
        }
        private ListItem[] GetAllNoticeImportances()
        {
            return new ListItem[]
            {
                //new ListItem("未设置","0")
                //,new ListItem("不重要","1")
                //,
                new ListItem("<img src='../../Images/Notice/Import0.png' style='width:15px;height:15px;'>普通","0")
                ,new ListItem("<img src='../../Images/Notice/Import1.png' style='width:15px;height:15px;'>比较重要","1")
                ,new ListItem("<img src='../../Images/Notice/Import2.png' style='width:15px;height:15px;'>很重要","2")
            };
        }
        private ListItem[] GetAllNoticeSta()
        {
            return new ListItem[]
            {
                new ListItem("自动","0")
                ,new ListItem("打开","1")
                ,new ListItem("关闭","2")
            };
        }
        private void BindListCtrl(object listData, object listCtrl, string textFormat, string defaultValue, string selectedValue)
        {
            if (listData is DataTable)
                BP.OA.UI.Dict.BindListCtrl((DataTable)listData, listCtrl, "Name", "No", textFormat, defaultValue, selectedValue);
            else if (listData is ListItem[])
                BP.OA.UI.Dict.BindListCtrl((ListItem[])listData, listCtrl, textFormat, defaultValue, selectedValue);
        }
        private int AddNotice(String Title, String Doc, String FK_NoticeCategory, String FK_Dept, int Importance
            , bool GetAdvices, String AdviceDesc, String AdviceItems, int NoticeSta, DateTime StartTime
            , DateTime StopTime, Boolean SendToPart, String SendToUsers, String SendToDepts, String SendToStations
            , String AttachFile, String[] Users)
        {
            BP.OA.Notice notice = new BP.OA.Notice();
            notice.Title = Title;
            
            notice.FK_NoticeCategory = FK_NoticeCategory.ToString();
            notice.RDT = Convert.ToDateTime(String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));
            notice.FK_Dept = FK_Dept;
            notice.FK_UserNo = BP.Web.WebUser.No;
            notice.Importance = Importance;
            notice.GetAdvices = GetAdvices;
            notice.SetTop = BP.OA.Main.CurDateTime;
            notice.SendToPart = SendToPart;
            notice.SendToDepts = SendToDepts;
            notice.SendToStations = SendToStations;
            notice.SendToUsers = SendToUsers;

            notice.AttachFile = AttachFile;
            //notice.SetMes = 0;
            if (GetAdvices)
            {
                notice.AdviceDesc = AdviceDesc;
                notice.AdviceItems = AdviceItems;
            }
            notice.NoticeSta = NoticeSta;
            if (NoticeSta == 0)
            {
                notice.StartTime = StartTime;
                notice.StopTime = StopTime;
            }
            notice.Insert();
            notice.Doc = Doc;
            notice.Update();
            if (notice.OID == 0)
            {
                this.Alert("插入失败！请联系管理员");
                return -1;
            }

            int iR = 0;
            foreach (String user in Users)
            {
                if (String.IsNullOrEmpty(user)) continue;
                NoticeReader nr = new NoticeReader();
                nr.MyPK = Guid.NewGuid().ToString();
                nr.FK_UserNo = user;
                nr.FK_NoticeNo = notice.OID.ToString();
                nr.AddTime = String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
                nr.Insert();
                iR++;
            }
            return notice.OID;
        }
        private void Alert(String msg)
        {
            BP.OA.Debug.Alert(this, msg);
        }
        /// <summary>
        /// 获取路径函数
        /// </summary>
        /// <returns></returns>
        private string GetAttachPathName()
        {
            string dir = String.Format("../../DataUser/UploadFile/Notice/{0:yyyyMMdd}", DateTime.Now);
            return dir;
        }
        /// <summary>
        /// 获取新文件名函数
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private string GetAttachFileName(string fileName)
        {
            string f = System.IO.Path.GetFileNameWithoutExtension(fileName);
            string ext = System.IO.Path.GetExtension(fileName);
            string newFileName = String.Format("{0}_{1:yyyyMMddHHmmss}{2}", f, DateTime.Now, ext);
            return newFileName;
        }
        /// <summary>
        /// 根据存储路径获取老文件名，必须是存储路径中包含老文件名才可。
        /// </summary>
        /// <param name="savePath"></param>
        /// <returns></returns>
        private string GetAttachOldFileName(string savePath)
        {
            String attachFile = System.IO.Path.GetFileName(savePath);
            String ext = System.IO.Path.GetExtension(savePath);
            //String[] arr_attachFile = attachFile.Split('_');
            //return String.Format("{0}{1}", arr_attachFile[0], ext);
            int index = attachFile.LastIndexOf('_');
            string oldName = attachFile.Substring(0, index);
            //String[] arr_attachFile = attachFile.Split('_');
            return String.Format("{0}{1}", oldName, ext);
        }
        #endregion

        #region //2.Load
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (!BP.OA.GPM.IsCanUseFun(this.FuncNo)) { BP.OA.GPM.RedirectNoAccess(); return; }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.LoadNoticeCategorys();
                this.LoadNoticeImportances();
                this.LoadNoticeNoticeSta();
                this.LoadDeptStruct();
            }
        }
        private void LoadNoticeCategorys()
        {
            this.BindListCtrl(this.GetAllNoticeCategory(), this.ui_FK_NoticeCategory, null, null, "04");
        }
        private void LoadDeptStruct()
        {
            //BP.OA.UI.Dict.BindListCtrl("SYS", "exec dbo.sp_get_tree_table 'Port_Dept','No','Name','ParentNo','No','0',1,4"
            //    , this.ui_FK_Dept, null, null, null);
            this.BindListCtrl(this.CurUserDepts, ui_FK_Dept, null, null, null);
        }
        private void LoadNoticeImportances()
        {
            this.BindListCtrl(this.GetAllNoticeImportances(), this.ui_Importance, null, null, "0");
        }
        private void LoadNoticeNoticeSta()
        {
            this.BindListCtrl(this.GetAllNoticeSta(), this.ui_NoticeSta, null, null, "1");
        }
        #endregion

        #region 3.Event
        protected void btnSubmit_Click(object sender, EventArgs e)
        {

            //1.获取UI变量
            String Title = this.ui_Title.Text;
            String Doc = this.ui_Doc.Text;
            String FK_NoticeCategory = this.ui_FK_NoticeCategory.SelectedValue;

            int Importance = Convert.ToInt32(this.ui_Importance.SelectedValue);

            String FK_Dept = null;
            if (!this.cb_Private.Checked) FK_Dept = this.ui_FK_Dept.SelectedValue;

            bool SendToPart = this.cb_Users.Checked;
            String SendToUsers = this.txt_UserNames.Value;
            String SendToDepts = this.txt_DeptNames.Value;
            String SendToStations = this.txt_StationNames.Value;

            bool GetAdvices = Convert.ToBoolean(this.ui_GetAdvices.Checked);
            String AdviceDesc = null;
            String AdviceItems = null;
            if (GetAdvices)
            {
                AdviceDesc = this.ui_AdviceDesc.Text;
                AdviceItems = this.ui_AdviceItems.Text;
            }

            int NoticeSta = Convert.ToInt32(this.ui_NoticeSta.SelectedValue);
            DateTime StartTime = System.DateTime.Now;
            DateTime StopTime = System.DateTime.Now;
            if (NoticeSta == 0)
            {
                StartTime = Convert.ToDateTime(String.Format("{0:yyyy-MM-dd HH:mm:ss}", this.ui_StartTime.Text));
                StopTime = Convert.ToDateTime(String.Format("{0:yyyy-MM-dd HH:mm:ss}", this.ui_StopTime.Text));
            }
            string[] users = null;
            if (!cb_Users.Checked)
            {
                DataTable dt = new DataTable();
                if (BP.WF.Glo.OSModel == BP.Sys.OSModel.OneMore)
                {
                    dt = BP.OA.GPM.GetFilteredEmps_BPM(SendToUsers, SendToDepts, SendToStations);
                }
                else
                {
                    dt = BP.OA.GPM.GetFilteredEmps(SendToUsers, SendToDepts, SendToStations);
                }
                String str_users = BP.OA.Main.GetValueListFromDataRowArray(dt.Select(), "{0}", ",", "No");
                users = str_users.Split(',');
            }
            else
            {
                List<String> ls = new List<string>();
                DataTable dt = BP.OA.GPM.GetAllEmps();
                foreach (DataRow dr in dt.Rows)
                {
                    if (!ls.Contains(Convert.ToString(dr["No"])))
                        ls.Add(Convert.ToString(dr["No"]));
                }
                users = ls.ToArray();
            }
            string AttachFile = null;

            //2.验证
            StringBuilder sbErrs = new StringBuilder();
            if (String.IsNullOrEmpty(FK_NoticeCategory))
            {
                sbErrs.Append("请选择通知类型!");
            }
            if (String.IsNullOrEmpty(Title))
            {
                sbErrs.Append("通知标题不能为空!");
            }
            if (String.IsNullOrEmpty(Doc))
            {
                sbErrs.Append(" 通知内容不能为空!");
            }
            if (users.Length == 0)
            {
                sbErrs.Append(" 请选择发送对象!");
            }
            if (sbErrs.Length != 0)
            {
                this.Alert(sbErrs.ToString());
                return;
            }

            //3.数据IO
            string dir = this.GetAttachPathName();
            if (!System.IO.Directory.Exists(Server.MapPath(dir)))
                System.IO.Directory.CreateDirectory(Server.MapPath(dir));
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];

                if (hpf.ContentLength > 0)
                {
                    string newFileName = this.GetAttachFileName(hpf.FileName);

                    string path = String.Format("{0}/{1}", dir, newFileName);
                    //string filePath = this.FileUpload1.PostedFile.FileName;
                    try
                    {
                        hpf.SaveAs(Server.MapPath(path));
                        AttachFile += String.Format("{0};", path);
                    }
                    catch
                    {
                        ;
                    }
                }
            }

            int oid = this.AddNotice(Title, Doc, FK_NoticeCategory, FK_Dept, Importance, GetAdvices,
                AdviceDesc, AdviceItems, NoticeSta, StartTime, StopTime, SendToPart, SendToUsers, SendToDepts,
                SendToStations, AttachFile, users);

            bool blnR = oid > 0;
            //4.统计与日志
            if (blnR)
            {
                //发短消息
                string userNos = String.Join(",", users);
                BP.OA.ShortMsg.Send_Notice(userNos, Title, "", oid.ToString(), false);
                //this.Alert("成功发布通知！");
                this.Response.Redirect("NoticeList.aspx", true);
            }
            else
            {
                this.Alert("发布通知失败！");
            }
        }
        #endregion
    }
}